<template>
  <view class="orders-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="title">我的订单</view>
      <view class="more-btn"></view>
    </view>
    
    <!-- 订单状态标签 -->
    <view class="status-tabs">
      <view 
        class="tab-item" 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ active: currentTab === index }"
        @tap="switchTab(index)"
      >
        <text>{{ tab }}</text>
        <view class="tab-line" v-if="currentTab === index"></view>
      </view>
    </view>
    
    <!-- 订单列表 -->
    <scroll-view class="order-list" scroll-y>
      <!-- 暂无订单 -->
      <view class="no-order" v-if="filteredOrders.length === 0">
        <image src="/static/images/no-order.png" mode="aspectFit"></image>
        <text>暂无订单</text>
      </view>
      
      <!-- 订单项 -->
      <view 
        class="order-item" 
        v-for="(order, index) in filteredOrders" 
        :key="index"
        @tap="goToOrderDetail(order.id)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-id">订单号：{{ order.id.substr(0, 8) }}...</text>
          <text class="order-status" :class="{'status-pending': order.status === 'pending', 'status-paid': order.status === 'paid', 'status-cancelled': order.status === 'cancelled'}">{{ getStatusText(order.status) }}</text>
        </view>
        
        <!-- 订单内容 -->
        <view class="order-content">
          <image :src="getScenicImage(order.scenicId)" mode="aspectFill" class="order-image"></image>
          <view class="order-info">
            <view class="scenic-name">{{ order.scenicName }}</view>
            <view class="ticket-name">{{ order.ticketName }} x {{ order.quantity }}</view>
            <view class="visit-date">游览日期: {{ formatDate(order.visitDate) }}</view>
          </view>
          <view class="order-price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ order.totalAmount }}</text>
          </view>
        </view>
        
        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="order-time">下单时间：{{ formatTime(order.createTime) }}</view>
          <view class="order-actions">
            <view class="action-btn cancel" @tap.stop="cancelOrder(order)" v-if="order.status === 'pending' || order.status === 'paid'">取消订单</view>
            <view class="action-btn print" @tap.stop="printTicket(order)" v-if="order.status === 'paid'">打印票据</view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { checkNeedLogin, getUserInfo } from '../../../utils/auth.js';

export default {
  data() {
    return {
      tabs: ['全部', '待付款', '已支付', '已取消'],
      currentTab: 0,
      orders: [],
      userInfo: null,
      scenicImages: {
        // 缓存景点图片
        1: 'http://114.55.56.174:19000/shzy/故宫.jpg',
        2: 'http://114.55.56.174:19000/shzy/八达岭长城.jpg',
        3: 'http://114.55.56.174:19000/shzy/颐和园.png',
        4: 'http://114.55.56.174:19000/shzy/大唐不夜城.png',
        5: 'http://114.55.56.174:19000/shzy/天坛公园.png',
        6: 'http://114.55.56.174:19000/shzy/鸟巢.png'
      }
    }
  },
  computed: {
    filteredOrders() {
      if (this.currentTab === 0) {
        return this.orders;
      } else if (this.currentTab === 1) {
        return this.orders.filter(order => order.status === 'pending');
      } else if (this.currentTab === 2) {
        return this.orders.filter(order => order.status === 'paid');
      } else if (this.currentTab === 3) {
        return this.orders.filter(order => order.status === 'cancelled');
      }
      return this.orders;
    }
  },
  onShow() {
    // 每次页面显示时重新加载订单
    if (checkNeedLogin()) return;
    this.getUserData();
    this.loadOrders();
  },
  onLoad() {
    if (checkNeedLogin()) return;
    this.getUserData();
    this.loadOrders();
  },
  methods: {
    // 获取用户信息
    getUserData() {
      this.userInfo = getUserInfo();
    },
    
    // 加载订单数据
    loadOrders() {
      try {
        // 从本地存储获取订单
        const allOrders = uni.getStorageSync('userOrders') || [];
        
        // 筛选当前用户的订单
        if (this.userInfo && this.userInfo.userId) {
          this.orders = allOrders.filter(order => order.userId === this.userInfo.userId);
        } else {
          this.orders = [];
        }
        
        // 按创建时间排序，最新的在前面
        this.orders.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        
        console.log('加载订单成功，订单数量：', this.orders.length);
      } catch (error) {
        console.error('加载订单失败:', error);
        this.orders = [];
      }
    },
    
    // 切换标签
    switchTab(index) {
      this.currentTab = index;
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      switch (status) {
        case 'pending': return '待付款';
        case 'paid': return '已支付';
        case 'cancelled': return '已取消';
        default: return '未知状态';
      }
    },
    
    // 获取订单状态类名
    getStatusClass(status) {
      switch (status) {
        case 'pending': return 'status-pending';
        case 'paid': return 'status-paid';
        case 'cancelled': return 'status-cancelled';
        default: return '';
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return '';
      const date = new Date(timeString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取景点图片
    getScenicImage(scenicId) {
      return this.scenicImages[scenicId] || '/static/images/default-scenic.jpg';
    },
    
    // 前往订单详情
    goToOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/user/orders/detail?orderId=${orderId}`
      });
    },
    
    // 取消订单
    cancelOrder(order) {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 获取所有订单
            const allOrders = uni.getStorageSync('userOrders') || [];
            
            // 找到当前订单的索引
            const orderIndex = allOrders.findIndex(o => o.id === order.id);
            
            if (orderIndex !== -1) {
              // 更新订单状态为已取消
              allOrders[orderIndex].status = 'cancelled';
              allOrders[orderIndex].cancelTime = new Date().toISOString();
              
              // 保存更新后的订单
              uni.setStorageSync('userOrders', allOrders);
              
              // 重新加载订单
              this.loadOrders();
              
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
            }
          }
        }
      });
    },
    
    // 打印票据
    printTicket(order) {
      uni.showToast({
        title: '正在生成票据...',
        icon: 'loading',
        duration: 1500
      });
      
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/user/orders/ticket?orderId=${order.id}`
        });
      }, 1500);
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss">
.orders-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .back-btn, .more-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
      color: #333;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.status-tabs {
  display: flex;
  justify-content: space-around;
  background: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
  
  .tab-item {
    position: relative;
    padding: 20rpx 0;
    
    text {
      font-size: 28rpx;
      color: #666;
    }
    
    &.active {
      text {
        color: #4080ff;
        font-weight: bold;
      }
      
      .tab-line {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background: #4080ff;
        border-radius: 2rpx;
      }
    }
  }
}

.order-list {
  padding: 20rpx 30rpx;
  height: calc(100vh - 120rpx);
  
  .no-order {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    
    image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 30rpx;
    }
    
    text {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .order-item {
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #eee;
      
      .order-id {
        font-size: 24rpx;
        color: #666;
      }
      
      .order-status {
        font-size: 26rpx;
        font-weight: bold;
        
        &.status-pending {
          color: #ff9500;
        }
        
        &.status-paid {
          color: #4080ff;
        }
        
        &.status-cancelled {
          color: #999;
        }
      }
    }
    
    .order-content {
      display: flex;
      padding: 20rpx 30rpx;
      border-bottom: 1rpx solid #eee;
      
      .order-image {
        width: 160rpx;
        height: 120rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .order-info {
        flex: 1;
        
        .scenic-name {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .ticket-name {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
        
        .visit-date {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .order-price {
        display: flex;
        align-items: baseline;
        
        .price-symbol {
          font-size: 24rpx;
          color: #ff4d4f;
        }
        
        .price-value {
          font-size: 36rpx;
          font-weight: bold;
          color: #ff4d4f;
        }
      }
    }
    
    .order-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      
      .order-time {
        font-size: 24rpx;
        color: #999;
      }
      
      .order-actions {
        display: flex;
        
        .action-btn {
          margin-left: 20rpx;
          padding: 10rpx 20rpx;
          border-radius: 30rpx;
          font-size: 24rpx;
          
          &.cancel {
            color: #666;
            border: 1rpx solid #ccc;
          }
          
          &.print {
            color: #fff;
            background: #4080ff;
          }
        }
      }
    }
  }
}
</style> 